//
/**
 * Filename: fig10-20_sigsetjum_longjmp.c
 * Author:   csbonkers
 * Contact:  forever65535@qq.com
 * Date:     2021/6/19
 * Description:
 *      信号屏蔽，sigsetjump,siglongjmp
 *      信号原子变量（sig_atomic_t） volatile修饰
 *      (调用系统定义的signal函数并不会预期的结果)
 */

#include "apue.h"
#include <setjmp.h>
#include <time.h>

static void sig_usr1(int signo);
static void sig_alrm(int signo);
static sigjmp_buf jmpenv;
static volatile sig_atomic_t canjmp;

int main(int argc, char *argv[]) {
  if (c_signal(SIGUSR1, sig_usr1) == SIG_ERR) {
    err_sys("signal(SIGUSR1) error");
  }
  if (c_signal(SIGALRM, sig_alrm) == SIG_ERR) {
    err_sys("signal(SIGALRM) error");
  }
  pr_mask("staring main: ");
  if (sigsetjmp(jmpenv, 1)) {
    pr_mask("ending main: ");
    exit(0);
  }
  canjmp = 1;
  for (;;) {
    pause();
  }
  return 0;
}
static void sig_usr1(int signo) {
  if (canjmp == 0) {
    return;// unexpected signal, ignore
  }
  pr_mask("starting sig_usr1: ");
  alarm(3);// SIGALRM in  3 seconds
  time_t starttime = time(NULL);
  for (;;) {// busy wait for 5 seconds
    if (time(NULL) > starttime + 5)
      break;
  }
  pr_mask("finishing sig_usr1: ");
  canjmp = 0;
  siglongjmp(jmpenv, 1);// jump back to main, don't return
}

static void sig_alrm(int signo) {
  pr_mask("in sig_alrm: ");
}